<?PHP
  class Language{
  
    public $languagePacks = null;
	public $language      = null;
	public $root          = "";
	
	public function __construct(){
	  $this->language = getSetting("global","global","language");
	}
	
	public function getString($token){
	  $packageName = $this->getLanguagePackName($token);
	  if(!$this->languagePacks[$packageName]){
	    $this->openLanguagePack($packageName);
	  }
	  if($this->languagePacks[$packageName]){
	    $res = $this->languagePacks[$packageName]->query("SELECT text FROM language WHERE token = '".$token."'");
        if($res){
		  return $res->fetchSingle();
		}
	  }
      return $token;
	}
	
	private function openLanguagePack($package){
	  if(!file_exists($this->getLanguagePackUrl($package))){
	    $create = true;
	  }
	  $this->languagePacks[$package] = new SQLiteDatabase($this->getLanguagePackUrl($package),0666);
	  if($create){
	    $this->languagePacks[$package]->queryExec('CREATE TABLE language (token nvarchar(50), text nvarchar(4000), PRIMARY KEY (token));');
	  }
	}
	
	private function getLanguagePackUrl($package){
	  $namespaces = split("_",strtolower($package));
	  if(sizeOf($namespaces) == 2){
	    if($namespaces[0] == "plugin"){
		  return $this->root."system/plugins/".$namespaces[1]."/language/".$this->language.".db";
		}
		else if($namespaces[0] == "skin"){
	      return $this->root."system/skins/".$namespaces[1]."/language/".$this->language.".db";
		}
	  }
	  return $this->root."system/language/".$this->language.".db";
	}
	
	private function getLanguagePackName($token){
	  $namespaces = split("_",strtolower($token));
	  if(sizeOf($namespaces) == 3){
	    if($namespaces[0] == "plugin"){
		  return "plugin_".$namespaces[1];
		}
		else if($namespaces[0] == "skin"){
		  return "skin_".$namespaces[1];
		}
	  }
	  return "global";
	}
	
	public function addTranslation($token,$text){
	  $packageName = $this->getLanguagePackName($token);
	  if(!$this->languagePacks[$packageName]){
	    $this->openLanguagePack($packageName);
	  }
	  if($this->languagePacks[$packageName]){
	    $this->languagePacks[$packageName]->queryExec("INSERT INTO language (token,text) VALUES ('".$token."','".$text."')");
	  }
	}

    public function deleteTranslation($token){
	  $packageName = $this->getLanguagePackName($token);
	  if(!$this->languagePacks[$packageName]){
	    $this->openLanguagePack($packageName);
	  }
	  if($this->languagePacks[$packageName]){
	    $this->languagePacks[$packageName]->queryExec("DELETE FROM language WHERE token = '".$token."'");
	  }
    }
  
  }
?>